//
//  QChargeBookDB.m
//  QoilPublic
//
//  Created by 杨凯 on 16/8/22.
//  Copyright © 2016年 杨凯. All rights reserved.
//

#import "QChargeBookDB.h"
#import "QChargeBookModel.h"
#import "QChargeBookShow.h"
@implementation QChargeBookDB
static FMDatabase *_db;

+ (void)initialize
{
    CLog(@"首次调用");
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [path stringByAppendingPathComponent:@"chargebookdb.sqlite"];
    _db = [FMDatabase databaseWithPath:filePath];
    //打开数据库
    if([_db open]){
        CLog(@"数据库打开成功");
    }else{
        CLog(@"数据库打开失败");
    }
    
    //创建表  //accountId 每条数据的id   userName 用户名    monthidStr 每个月数据的id    createTime 排序的创建时间    dict 总数据
   BOOL isExist = [_db tableExists:@"chargeBook_list"];
    if(!isExist){
       BOOL flag = [_db executeUpdate:@"create table if not exists chargeBook_list (id integer primary key autoincrement,accountId text,userName text,monthidStr text,createTime text,dict blob)"];
        if(flag){
            CLog(@"创建表成功");
        }else{
            CLog(@"创建表失败");
        }
    }else{
    
        CLog(@"表已存在");
    }
}

//插入数据
+ (BOOL)saveChargeBookDataWithaccountId:(NSString *)accountId monthidStr:(NSString *)monthidStr createTime:(NSString *)createTime dataDic:(NSDictionary *)dataDic
{
    
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataDic];
    BOOL flag = [_db executeUpdate:@"insert into chargeBook_list (accountId,userName,monthidStr,createTime,dict) values(?,?,?,?,?)",accountId,userName,monthidStr,createTime,data];
    if(flag){
        CLog(@"插入成功");
    }else{
        CLog(@"插入失败");
    }
    return flag;
}

//插入更新的数据
+ (void)saveChargeBookUpdateAllData:(NSArray *)array successBlock:(void(^)())block{
    
     BOOL isRollBack = NO;
     NSString *userName = [QUserInfo sharedInfo].loginModel.tel;
    [_db beginTransaction];
        @try {
            for(NSDictionary *dic in array){
                NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dic];
                BOOL flag = [_db executeUpdate:@"insert into chargeBook_list (accountId,userName,monthidStr,createTime,dict) values(?,?,?,?,?)",dic[@"accountId"],userName,[NSString stringWithFormat:@"%@%@",dic[@"year"],dic[@"month"]],dic[@"createTime"],data];
                if(flag){
                    CLog(@"插入成功");
                }else{
                    CLog(@"插入失败");
                }
            }
            block();
        } @catch (NSException *exception) {
    
            isRollBack = YES;
            [_db rollback];
    
        } @finally {
    
            if (!isRollBack) {
                [_db commit];
            }
        }
}

//查询数据
+ (NSArray *)queryChargeBookData
{
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;
    NSString *sql = [NSString stringWithFormat:@"select * from chargeBook_list where userName = '%@' order by createTime desc",userName];
    
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *arry = [NSMutableArray array];
    
    while ([set next]) {
        NSData *data = [set dataForColumn:@"dict"];
        NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [arry addObject:dict];
    }
    
    return arry;
}

//修改数据
+ (BOOL)updateSetDataWithaccountId:(NSString *)accountId dataDic:(NSDictionary *)dataDic monthidStr:(NSString *)monthidStr createTime:(NSString *)createTime
{
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dataDic];
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;

    BOOL flag = [_db executeUpdate:@"update chargeBook_list set dict = ?,userName = ?, monthidStr = ?, createTime = ? where accountId = ?",data,userName,monthidStr,createTime,accountId];
     if(flag){
        CLog(@"修改成功");
     }else{
        CLog(@"修改失败");
     }
    return flag;
}

//删除某一条数据
+ (BOOL)deleteChargeBookDataWithaccountId:(NSString *)accountId
{
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;

    NSString *sql = [NSString stringWithFormat:@"delete from chargeBook_list where accountId = '%@' and userName = '%@'",accountId,userName];
    BOOL flag = [_db executeUpdate:sql];
      if(flag){
          CLog(@"删除成功");
      }else{
          CLog(@"删除失败");
      }
    return flag;
}

//删除对应的月数据
+ (void)deleteChargeBookDataWithYearMonth:(NSString *)yearMonth successsBlock:(void(^)())block;
{
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;

    NSString *sql = [NSString stringWithFormat:@"delete from chargeBook_list where monthidStr = '%@' and userName = '%@'",yearMonth,userName];
    BOOL flag = [_db executeUpdate:sql];
    if(flag){
        CLog(@"删除成功");
        
    }else{
        CLog(@"删除失败");
    }
    block();
}

//记账本主页三条数据
+ (NSArray *)queryMainPageData:(NSString *)monthidStr;
{
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;
    NSString *sql = [NSString stringWithFormat:@"select * from chargeBook_list where userName = '%@' and monthidStr = '%@' order by createTime desc limit 3",userName,monthidStr];
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *arry = [NSMutableArray array];
    
    while ([set next]) {
        NSData *data = [set dataForColumn:@"dict"];
        NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [arry addObject:dict];
    }
    return arry;
}

//记账本主页一个月的数据
+ (NSArray *)queryMainPageWithMonthData:(NSString *)monthidStr;
{
    NSString *userName = [QUserInfo sharedInfo].loginModel.tel;
    NSString *sql = [NSString stringWithFormat:@"select * from chargeBook_list where userName = '%@' and monthidStr = '%@'",userName,monthidStr];
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *arry = [NSMutableArray array];
    
    while ([set next]) {
        NSData *data = [set dataForColumn:@"dict"];
        NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [arry addObject:dict];
    }
    return arry;
}

//设置数据
+ (NSMutableArray *)setupChargeBookData:(NSArray *)arr
{
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
    for (NSDictionary *dic in arr) {
        NSString *year = dic[@"year"];
        NSString *month = dic[@"month"];
        NSString *allStr = [NSString stringWithFormat:@"%@%@",year,month];//201508 201608 201608
        NSArray *keys =dataDic.allKeys;
        if([keys containsObject:allStr]){
            NSMutableArray *oldArr = dataDic[allStr];
            [oldArr addObject:dic];
            [dataDic setObject:oldArr forKey:allStr];
        }else{
            NSMutableArray *dataArr = [NSMutableArray array];
            [dataArr addObject:dic];
            [dataDic setObject:dataArr forKey:allStr];
        }
    }
    
    NSMutableArray *_keyArr = [NSMutableArray array];
    [_keyArr addObjectsFromArray:dataDic.allKeys];
    NSSortDescriptor *distanceDescriptor = [[NSSortDescriptor alloc] initWithKey:nil ascending:NO];
    NSArray *descriptors = [NSArray arrayWithObjects:distanceDescriptor,nil];
    [_keyArr sortUsingDescriptors:descriptors];//排序后的key数组
    
    NSMutableArray *_allData = [NSMutableArray array];
    for (int i=0; i<_keyArr.count; ++i) {//根据排序后的key数组按顺序加到数组里面
        NSArray *arr = dataDic[_keyArr[i]];//这是每一个月的数据
        NSArray *monthArr = (NSArray *)[QChargeBookModel objectArrFromDictArr:arr];//把每一个月数据转换成模型
        [_allData addObject:monthArr];//里面有多个少数组代表多少月，每个数组里面有多少model
    }
    return _allData;
}

//配置文件路径
+ (NSString *)fileCreate:(NSString *)path
{
    NSString *documentDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    
    NSString *fielDirectory = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"file%@",[QUserInfo sharedInfo].loginModel.tel]];//文件夹路径
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:fielDirectory]) {
        BOOL res=[fileManager createDirectoryAtPath:fielDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        if (res) {
            NSLog(@"文件夹创建成功");
        }else
            NSLog(@"文件夹创建失败");
    }

    NSString *filePath = [fielDirectory stringByAppendingPathComponent:path];//文件路径
    CLog(@"filePath=%@", filePath);
    if (![fileManager fileExistsAtPath:filePath]) {
        [fileManager createFileAtPath:filePath contents:nil attributes:nil];
    }
    return filePath;
}

//写配置文件
+ (void)writeFileByArray:(NSString *)filePath arrData:(NSMutableArray *)arrData successBlock:(void(^)())block
{
    NSString *s = [QParamService arrToString:arrData];
    BOOL success = [s writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if(success){
        block();
    }
}

//读配置文件
+ (NSMutableArray *)readDataArrToFilePath:(NSString *)filePath
{
    NSString *content=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableArray *arr = (NSMutableArray *)[NSJSONSerialization JSONObjectWithData:jsonData
                                                                                      options:NSJSONReadingMutableContainers
                                                                                        error:nil];
    return arr;
}

//提交配置文件给服务器
+ (NSData *)submitProfileDataToSever:(NSString *)filePath
{
    NSString *content=[NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
    return jsonData;
}

//公用的写配置文件回调
+ (void)writeProfileByYearMonth:(NSString *)yearMonth time:(NSString *)time successBlock:(void(^)(NSString *arrf))block
{

    NSString *arrFile = [QChargeBookDB fileCreate:@"accountSetting"];//配置文件路径
    NSMutableArray *arr = [QChargeBookDB readDataArrToFilePath:arrFile];
    if(arr){
        for (int i=0; i<arr.count; ++i) {//判断查找是否有修改月的配置文件数据，有的话就说明修改，没有的话说明增加
            NSMutableDictionary *d = arr[i];
            NSString *fileName = d[@"fileName"];
            if([fileName containsString:[NSString stringWithFormat:@"accountFile%@",yearMonth]]){
                [arr removeObjectAtIndex:i];
                break;
            }
        }
        
        NSMutableDictionary *d = [NSMutableDictionary dictionary];
        [d setObject:time forKey:@"editTime"];
        [d setObject:[NSString stringWithFormat:@"accountFile%@",yearMonth] forKey:@"fileName"];
        [arr addObject:d];
        [QChargeBookDB writeFileByArray:arrFile arrData:arr successBlock:^{
            if(block){
                block(arrFile);
            }
        }];
    }else{
        NSMutableArray *a = [NSMutableArray array];
        NSMutableDictionary *d = [NSMutableDictionary dictionary];
        [d setObject:time forKey:@"editTime"];
        [d setObject:[NSString stringWithFormat:@"accountFile%@",yearMonth] forKey:@"fileName"];
        [a addObject:d];
        [QChargeBookDB writeFileByArray:arrFile arrData:a successBlock:^{
            if(block){
                block(arrFile);
            }
        }];
    }
}

//当前的周几
+ (NSString *)currentWeek
{
    NSArray *weekday = @[@"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六",@""];
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitWeekday|NSCalendarUnitDay fromDate:[NSDate date]];
    NSString *weekStr = [weekday objectAtIndex:components.weekday-1];
    return weekStr;
}

//初始化年月日时间
+ (void)formatDate:(NSString *)str successBlock:(void(^)(NSString *y,NSString *m,NSString *d,NSString *t))block
{
    NSString *y; NSString *m; NSString *d; NSString *t;
    NSArray *arr = [str componentsSeparatedByString:@"/"];
    if(arr.count){
        y = arr[0];
        NSString *s = arr[1];
        NSArray *arr1 = [s componentsSeparatedByString:@" "];//03-04
        if(arr1.count){
            NSString *s1 = arr1[0];
            NSArray *arr2 = [s1 componentsSeparatedByString:@"-"];
            if(arr2.count){
                m = arr2[0];
                d = arr2[1];
            }
            t = arr1[1];
        }
    }
    if(block){
        block(y,m,d,t);
    }
}


@end
